<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 用户管理
 */
class Users extends Auth_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('users_mdl');
        $this->load->model('uinfo_mdl');
        $this->load->model('group_mdl');
    }

    /**
     * 查看用户下线
     */
    public function subordinate(){

    }

    public function index(){
        if($_SESSION['user']['status'] != 1){
            show_error('您没有权限打开该页面');
        }
        /** 查询条件组装 */
        $url = '';
        $this->db->start_cache();
        $this->db->where('status !=',4);
        $group = $this->input->get('group');
        if(!empty($group)){
            if($group === "admin"){
                $this->db->where('users.status',2);
            }else{
                $group = intval($group);
                $this->db->where('users.group_id',$group);
                $this->db->where('users.status',3);
            }
            $url .= 'group='.$group.'&';
        }

        $keywords = $this->input->get('keywords');
        if(!empty($keywords)){
            $this->db->like('users.username',$keywords);
            $this->db->or_like('users_info.name',$keywords);
            $url .= 'keywords='.$keywords.'&';
        }
		$uid = $this->input->get('uid');

		if(intval($uid) > 0){
			$this->db->where('users.id',$uid);
		}

        $this->db->from('users');
        $this->db->select('*');
        $this->db->order_by('users.status desc,users.id desc');
        $this->db->join('users_info','users_info.id = users.id','left');
        $this->db->stop_cache();

        $this->load->library('pagination');

        if(!empty($url)){
            $url = '?'.substr($url, 0 , -1);
        }

        $config['base_url'] = site_url('users/index').$url;
        $config['total_rows'] = $this->db->count_all_results();
        $config['per_page'] = 10;
        $config['page_query_string'] = TRUE;
        $config['first_link'] = '首页';
        $config['last_link'] = '尾页';
        $config['next_link'] = '下一页';
        $config['prev_link'] = '上一页';
        $config['anchor_class'] = 'current';

        $this->pagination->initialize($config);
        $data['page'] = $this->pagination->create_links();

        $per_page = $this->input->get('per_page');
        $this->db->limit($config['per_page'],intval($per_page));
        $list = $this->db->get()->result_array();
        //$list = $this->users_mdl->select();
        //echo $this->db->last_query();
        $this->db->flush_cache();

        $group_list = $this->group_mdl->select();
        foreach($list as $k => $v){
            if($v['status'] == 1){
                $list[$k]['group'] = '超级管理员';
            }
            if($v['status'] == 2){
                $list[$k]['group'] = '管理员';
            }

            foreach($group_list as $key => $value){
                if($v['group_id'] == $value['id']){
                    $list[$k]['group'] = $value['title'];
                }
            }

            //查询用户上级用户

            if($v['pid'] == 0){
                $list[$k]['puser'] = array(
                    'id' => 0,
                    'username' => '----'
                );
            }else{
                $this->db->where('id',$v['pid']);
                $this->db->select('id,username,pid');
                $list[$k]['puser'] = $this->users_mdl->get_one();
            }
        }
        $data['list'] = $list;
        $data['group_list'] = $group_list;
        $this->_view('index',$data);
    }

    /**
     * 用户所有上级
     */
    public function from(){
        if($_SESSION['user']['status'] != 1){
            show_error('您没有权限打开该页面');
        }
        $uid = $this->input->get('uid');
        if(!is_numeric($uid) || $uid < 1){
            show_error('参数错误！');
        }

        $list = $this->users_mdl->get_from($uid);

        if(count($list) < 2){
            show_error('该用户没有上级');
        }

        //查询全部用户特权
        $group_list = $this->group_mdl->select();

        //查询用户资料
        foreach($list as $k => $v){
            $this->db->where('id',$v['id']);
            $uinfo = $this->uinfo_mdl->get_one();
            $list[$k]['uinfo'] = $uinfo;

            foreach($group_list as $key => $value){
                if($v['group_id'] == $value['id']){
                    $list[$k]['group'] = $value['title'];
                }
            }
        }

        $data = array(
            'list' => $list
        );
        $this->_view('from',$data);
    }

    /**
     * 查询用户所有下线
     */
    public function junior(){
        if($_SESSION['group'] != 3){
            show_error('没有权限打开该页面');
        }

        $tier = $this->input->get('tier');
        $tier = intval($tier);

        $this->db->where('id',$_SESSION['user']['id']);
        $this->db->select('tier,group_id');
        $utier = $this->users_mdl->get_one();
        if(empty($tier)){
            $tier = $utier['tier'];
        }

        $pid = $this->input->get('pid');
        $pid = intval($pid);

        if(empty($pid)){
            $pid = $_SESSION['user']['id'];
        }

        //查询对应下级
        $this->db->where('tier',$tier+1);
        $this->db->where('pid',$pid);
        $list = $this->users_mdl->select();

        $group_list = $this->group_mdl->select();
        //查询当前用户的权限金额（判断是否有权限查看下级用户）
        $group = array();
        foreach($group_list as $k => $v){
            if($utier['group_id'] == $v['id']){
                $group = $v;
            }
        }

        foreach($list as $k => $v){
            $this->db->where('id',$v['id']);
            $list[$k]['uinfo'] = $this->uinfo_mdl->get_one();

            foreach($group_list as $key => $value){
                if($v['group_id'] == $value['id']){
                    $list[$k]['group'] = $value;
                }
            }
        }

        $data = array(
            'list' => $list,
            'tier' => $tier-$utier['tier'],    //当前查询用户层级
            'group' => $group
        );
        $this->_view('junior',$data);
    }
    /**
     * 获取用户推广链接
     */
    public function promotion(){
        if($_SESSION['group'] != 3){
            show_error('没有权限打开该页面');
        }

        $this->load->model('article_mdl');
        $this->load->model('config_mdl');
        //获取推广文章
        $this->db->where('id',1);
        $this->db->select('article_id');
        $config = $this->config_mdl->get_one();

        $this->db->where('id',$config->article_id);
        $this->db->select('content');

        $article = $this->article_mdl->get_one();

        //判断是否是手机端， 获取微信分享链接

        $this->_view('promotion',array(
                'content' => $article['content'],
                'url' => site_url('welcome/registered?puid='.$_SESSION['user']['id'])
            )
        );


    }

    /**
     * 用户删除
     */
    public function delete(){
        if(!$this->input->is_ajax_request()){
            show_error('参数错误！ ');
        }

        $uid = $this->input->post('uid');
        $uid = intval($uid);

        if(empty($uid)){
            die('参数错误!');
        }
        $this->db->where('id',$uid);
        $res = $this->users_mdl->update(array('status'=>4));
        echo $res === true ? '1' : '操作失败！';
    }

    /**
     * 密码重置
     */
    public function reset_pwd(){
        if($_SESSION['user']['status'] != 1){
            show_error('您没有权限打开该页面');
        }

        if($this->input->is_ajax_request()){
            $post = $this->input->post();
            //验证密码
            if(!preg_match("/\w{6,20}/",$post['pwd'])){
                die('密码格式不正确， 请输入字母、数字、下划线，6-20个字符');
            }
            if($post['pwd'] != $post['pwd1']){
                die('两次密码输入不一致');
            }

            $this->db->where('id',intval($post['uid']));
            $res = $this->users_mdl->update(array('password'=>md5($post['pwd'])));
            echo $res === true ? 1 : '重置密码失败！';
        }else{
            $uid = $this->input->get('uid');
            $uid = intval($uid);
            $this->db->where('id',$uid);
            $user = $this->users_mdl->get_one();
            $this->_view('reset_pwd',array('user'=>$user));
        }
    }

    /**
     * 用户修改
     */
    public function update(){
        if($this->input->is_ajax_request()){
            $post = $this->input->post();

            $uid = intval($post['uid']);
            if($_SESSION['user']['status'] != 1 && $_SESSION['user']['id'] != $uid){
                die('权限不足，修改失败！');
            }

            if($post['status'] == 2){
                $post['group_id'] == 0;
            }

            if(empty($post['name'])){
                die('真实姓名不能为空');
            }

            if(!preg_match("/^1[0-9]{10}$/",$post['phone'])){
                die('联系电话格式错误，请填写11位的手机号码');
            }

            if(!preg_match("/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/",$post['email'])){
                die('联系邮箱格式错误，请填写正确的邮箱地址，如 zbzmall@163.com');
            }

            if(!preg_match("/^[0-9]{6,14}$/",$post['qq']) && !empty($post['qq'])){
                die('请正确填写QQ');
            }

            if(!preg_match("/^[a-zA-Z0-9_]{2,30}$/",$post['weixin']) && !empty($post['weixin'])){
                die('请正确填写微信帐号');
            }

            $data = array(
                'status' => intval($post['status']),
                'group_id' => $post['group_id']
            );
            $this->db->where('id',$uid);
            $user_id = $this->users_mdl->update($data);

            $data = array(
                'name' => $post['name'],
                'phone' => $post['phone'],
                'qq' => $post['qq'],
                'address' => $post['address'],
                'weixin' => $post['weixin'],
                'email' => $post['email'],
                'company' => $post['company']
            );

            $this->db->where('id',$uid);
            $res = $this->uinfo_mdl->update($data);
            echo $res === true ? 1 : '操作失败！';
        }else{
            if($_SESSION['user']['status'] == 1){
                $uid = $this->input->get('uid');
                $uid = intval($uid);
            }else{
                $uid = $_SESSION['user']['id'];
            }

            if(empty($uid)){
                $uid = $_SESSION['user']['id'];
            }

            $this->db->where('id',$uid);
            $user = $this->users_mdl->get_one();

            if(empty($user)){
                die('该用户不存在');
            }
            $this->db->where('id',$uid);
            $info = $this->uinfo_mdl->get_one();
            $this->db->order_by('condition desc');
            $groups = $this->group_mdl->select();

            $this->_view('update',array('user'=>$user,'info'=>$info,'groups'=>$groups));
        }
    }

    /**
     * 新增用户
     */
    public function create(){
        if($this->input->is_ajax_request()){
            $post = $this->input->post();
            /** 数据判断 */
            if(!preg_match("/\w{6,20}/",$post['user_name'])){
                die('登录帐号格式不正确， 请输入字母、数字、下划线，6-20个字符');
            }

            $this->db->where('username',$post['user_name']);
            $res_is = $this->users_mdl->get_count();
            if(!empty($res_is)){
                die('该登录帐号已经存在，请修改');
            }

            if($post['pass'] != $post['password_1']){
                die('两次密码输入不一致');
            }
            if(!preg_match("/\w{6,20}/",$post['pass'])){
                die('密码格式不正确， 请输入字母、数字、下划线，6-20个字符');
            }

            if($post['status'] == 2){
                $post['group_id'] == 0;
            }

            if(empty($post['name'])){
                die('真实姓名不能为空');
            }

            if(!preg_match("/1[0-9]{10}/",$post['phone'])){
                die('联系电话格式错误，请填写11位的手机号码');
            }

            if(!preg_match("/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/",$post['email'])){
                die('联系邮箱格式错误，请填写正确的邮箱地址，如 zbzmall@163.com');
            }

            if(!preg_match("/^[0-9]{6,14}$/",$post['qq']) && !empty($post['qq'])){
                die('请正确填写QQ');
            }

            if(!preg_match("/^.{5，30}$/",$post['weixin']) && !empty($post['weixin'])){
                die('请正确填写微信帐号');
            }

            $data = array(
                'username' => $post['user_name'],
                'password' => md5('pass'),
                'login_time' => time(),
                'status' => intval($post['status']),
                'create_time' => time(),
                'group_id' => $post['group_id']
            );
            $this->db->trans_start();
            $user_id = $this->users_mdl->create($data);

            $data = array(
                'id' => $user_id,
                'name' => $post['name'],
                'phone' => $post['phone'],
                'qq' => $post['qq'],
                'address' => $post['address'],
                'weixin' => $post['weixin'],
                'email' => $post['email'],
                'company' => $post['company'],
                'money' => 0
            );

            $res = $this->uinfo_mdl->create($data);
            $this->db->trans_complete();

            if ($this->db->trans_status() === FALSE){
                die('数据处理失败，请联系网站管理员处理');
            }

            echo $res ? 1 : '添加用户失败！';


        }else{
            $this->db->order_by('condition desc');
            $groups = $this->group_mdl->select();
            $this->_view('create',array('groups'=>$groups));
        }
    }

    /**
     * 新增权限
     */
    public function create_group(){

    }

    /**
     * 密码修改
     */
    public function set_pwd(){

        if($this->input->is_ajax_request()){
            $post = $this->input->post(NULL);
            //验证密码
            if(!preg_match("/\w{6,20}/",$post['pwd'])){
                die('密码格式不正确， 请输入字母、数字、下划线，6-20个字符');
            }
            if($post['pwd'] != $post['pwd1']){
                die('两次密码输入不一致');
            }
            $this->db->where('id',$_SESSION['user']['id']);
            $this->db->where('password',md5($post['old_pwd']));

            $is = $this->users_mdl->get_count();
            if(empty($is)){
                die('原密码不正确');
            }

            if($post['old_pwd'] == $post['pwd']){
                die(1);
            }

            $this->db->where('id',$_SESSION['user']['id']);
            $res = $this->users_mdl->update(array('password' => md5($post['pwd'])));

            echo $res === true ? '1' : '密码修改失败';
        }else{
            $this->_view('set_pwd');
        }
    }

    /**
     * 用户退出
     */
    public function outuser(){
        $this->session->sess_destroy();
        redirect(site_url('welcome/index'));
    }

}

/* End of file Users.php */
/* Location: ./application/controllers/Users.php */